package com.archie.xunji.guanzhu;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.IBinder;

import java.io.IOException;

/**
 * Created by xqx on 2015/11/11.
 */
public class PlayService extends Service{
    //媒体文件播放组件
    private MediaPlayer mPlay;
    private int sumTime;
    private int curTime;

    @Override
    public void onCreate() {
        super.onCreate();

        mPlay = MediaPlayer.create(getApplicationContext(), Uri.parse(""));
        //获得播放文件总时长
        sumTime = mPlay.getDuration();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //判断当前意图是否要播放新的音频文件，true播放，false不播放
        final String musicUrl = intent.getStringExtra("musicUrl");
        if (intent.getBooleanExtra(Configs.EXTRA_CHANGE,false)){
            //如果要播放新的音频，则重置播放器
            mPlay.reset();
            try {
                mPlay.setDataSource(musicUrl);
                //进入就绪状态
                mPlay.prepare();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //判断当前的MediaPlayer是否正在播放
            if (mPlay.isPlaying()){
                mPlay.pause();
            }else{
                mPlay.start();
                new ProgressThread().start();
            }
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //停止播放
        mPlay.stop();
        //释放资源
        mPlay.release();

    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    //计算播放进度的线程
    class ProgressThread extends Thread{
        @Override
        public void run() {
            super.run();
            while (mPlay!=null&&mPlay.isPlaying()){
                sumTime = mPlay.getDuration();
                curTime = mPlay.getCurrentPosition();
                //发送 广播
                Intent intent = new Intent(Configs.ACTION_PROGRESS);
                intent.putExtra(Configs.EXTRA_PROGRESS_MAX,sumTime);
                intent.putExtra(Configs.EXTRA_PROGRESS_CUR,curTime);
                sendBroadcast(intent);
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
